<template>

  <div class="search">
    <span>项目状态：</span>
    <el-input class="input" v-model="serachInfo" size="large" placeholder="请输入"></el-input>
    <el-button class="button" size="large" type="primary" plain @click="searchScreen">搜索</el-button>
    <el-button class="button" size="large" type="primary" plain>添加</el-button>
    <el-button class="button" size="large" type="primary" plain @click="refreshScreen">刷新</el-button>
  </div>

  <el-table :data="filterTableData" style="width: 100%" :header-cell-style="headerClass">
    <el-table-column prop="title" label="项目标题" width="180" class-name="title-w"/>
    <el-table-column prop="description" label="项目描述" width="360"/>
    <el-table-column prop="content" label="项目详情内容" width="600" show-overflow-tooltip/>
    <el-table-column prop="status" label="状态" width="80">
      <template #default="scope">
        <el-tag
            :type="getStatusConfig(scope.row.status).tpye"
            effect="dark"
            round
        >
          {{ getStatusConfig(scope.row.status).viewpage }}
        </el-tag>
      </template>
    </el-table-column>
    <el-table-column :formatter="(value) => detaFormater(value.createTime)" prop="createTime" label="创建时间"
                     width="150"/>
    <el-table-column :formatter="(value) => detaFormater(value.updateTime)" prop="updateTime" label="更新时间"
                     width="150"/>
    <el-table-column align="right">
      <template #header>
        <el-input v-model="search" size="small" placeholder="查询的项目标题/描述" class="search_table"/>
      </template>
      <el-table-column label="操作" align="left" label-class-name="centered-label">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">
            <span>编辑</span>
          </el-button>
          <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
          >
            <span>删除</span>
          </el-button>
        </template>
      </el-table-column>
    </el-table-column>
  </el-table>
  <div class="demo-pagination-block">
    <div class="box_position">
      <el-pagination

          :disabled="disabled"
          :background="background"
          layout="prev, pager, next, jumper"
          :total="total"
          @current-change="handleCurrentChange"
          :default-page-size="pageSize"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import api from "@/api/index.js";
import {onMounted, reactive, computed, ref, onBeforeUnmount} from "vue"
import {detaFormater} from "@/utils/date.js"
import {ElLoading, ComponentSize} from 'element-plus'

const projectInfo = reactive({
  list: []
})

const getStatusConfig = (status) => {
  return new StatusConfig(status);
};

class StatusConfig {

  constructor(status) {
    this.status = status;
    this.init();
  }

  init() {
    switch (this.status) {
      case 1:
        this.name = "1";
        this.viewpage = "上架";
        this.tpye = 'success';
        break;
      case 0:
        this.name = "0";
        this.viewpage = "下架";
        this.tpye = 'danger';
        break;
      default:
        this.name = "unknown";
        this.viewpage = "未知";
        this.tpye = 'info';
    }
  }
}


onMounted(() => {
  initialization(0)
})
const initialization = (size) => {
  return api.getpageparameter({
    page: size,
    size: 10
  }).then(res => {
    if (res.data !== null) {
      projectInfo.list = res.data.content
      total.value = res.data.totalElements
    }
    return res;
  }).catch(error => {
    console.log(error);
    return error;
  });
}


const handleApiRequest = (apiCall, successCall, errorCall) => {
  return apiCall()
      .then(res => {
        if (res.data !== null && successCall) {
          successCall(res.data);
        }
        return res;
      })
      .catch(error => {
        console.log(error);
        if (errorCall) {
          errorCall(error);
        }
        return error;
      });
};


const http = (showLoading = true) => {
  let loadingInstance = null;
  if (showLoading) {
    loadingInstance = ElLoading.service({
      lock: true,
      svgViewBox: "-10, -10, 50, 50",
      text: 'Loading',
      background: 'rgba(122, 122, 122, 0.8)',
    });
  }

  const cleanup = () => {
    if (loadingInstance) {
      loadingInstance.close();
    }
  };

  return handleApiRequest(
      () => api.getallproject(),
      (data) => {
        projectInfo.list = data;
        console.log(data);
      },
      (error) => {
        console.log('请求失败:', error);
      }
  ).finally(cleanup);
};


const refreshScreen = () => {
  return api.getpageparameter({
    page: 0,
    size: 10
  }).then(res => {
    if (res.data !== null) {
      projectInfo.list.splice(0, projectInfo.list.length, ...res.data.content);
      total.value = res.data.totalElements
      console.log(projectInfo.list)
      console.log(total.value)
    }
    return res;
  }).catch(error => {
    console.log(error);
    return error;
  });
};


const headerClass = () => {
  return {
    background: "#dcdcdc",
    color: "#999",
    fontWeight: 700
  }
}


const search = ref('')
const filterTableData = computed(() =>
    projectInfo.list.filter((data) => {
      const lowerSearch = search.value.toLowerCase();
      let statusFilter = '';
      if (lowerSearch.includes('上架')) {
        statusFilter += '1';
      }
      if (lowerSearch.includes('下架')) {
        statusFilter += '0';
      }
      return (
          !search.value ||
          data.title.toLowerCase().includes(lowerSearch) ||
          data.description.toLowerCase().includes(lowerSearch) ||
          statusFilter && data.status.toString().includes(statusFilter)
      );
    })
);
const handleEdit = (index: number, row) => {
  console.log(index, row)
}
const handleDelete = (index: number, row) => {
  console.log(index, row)
}


const serachInfo = ref()


const svg = `
        <path class="path" d="
          M 30 15
          L 28 17
          M 25.61 25.61
          A 15 15, 0, 0, 1, 15 30
          A 15 15, 0, 1, 1, 27.99 7.5
          L 15 15
        " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>
      `


const searchScreen = () => {
  blurAll();
}

const blurAll = (showLoading = true) => {
  let loadingInstance = null;
  if (showLoading) {
    loadingInstance = ElLoading.service({
      lock: true,
      svgViewBox: "-10, -10, 50, 50",
      text: 'Loading',
      background: 'rgba(122, 122, 122, 0.8)',
    });
  }

  const cleanup = () => {
    if (loadingInstance) {
      loadingInstance.close();
    }
  };

  return handleApiRequest(
      () => api.getblurAll({value: serachInfo.value}),
      (data) => {
        projectInfo.list.splice(0, projectInfo.list.length, ...data);
        console.log(data);
      },
      (error) => {
        console.log('请求失败:', error);
      }
  ).finally(cleanup);
};

onBeforeUnmount(() => {
  projectInfo.list = []
  search.value = ''
  serachInfo.value = ''
  try {
    const loadingInstance = ElLoading.service({})
    loadingInstance.close()
  } catch (e) {
    console.log(e)
  }
})


const currentPage = ref(1)
const pageSize = ref(10)
const background = ref(false)
const disabled = ref(false)
const total = ref(0)


const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
  CurrentChangehttp(val)
}

const CurrentChangehttp = (value) => {
  api.getpageAll({
    offset: (value - 1) * pageSize.value,
    pageSize: pageSize.value
  }).then(res => {

    projectInfo.list.splice(0, projectInfo.list.length, ...res.data.pageResult.records);
    console.log(res.data.pageResult)
  })
}
</script>


<style>
.title-w {
  font-weight: bold;
}


.search {
  margin-top: 10px;
  padding: 10px;
  width: 100%;
  background-color: rgba(244, 232, 9, 0.85);
  box-sizing: border-box;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.search span {

  font-weight: 700;
}

.search .input {
  width: 300px;
}

.search_table {
  margin-right: 200px;
}

.centered-label {
  display: flex;
  justify-content: center;
}

.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}

.box_position {
  right: 30px;

}


</style>